//
//  StaffEditMessageVC.m
//  New_Runway
//
//  Created by mack on 2018/2/7.
//  Copyright © 2018年 NelsonJ. All rights reserved.
//

#import "StaffEditMessageVC.h"
#import "EditUserMessageCell.h"
@interface StaffEditMessageVC ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>
@property(nonatomic, strong) UITableView *tableview;
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *phone;
@end

@implementation StaffEditMessageVC

- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationBarView.titleLabel.text = self.mainTitle;
    self.view.backgroundColor = kColorWhite();
    [self initTableview];
    if (self.type == 1) {
        self.name = self.mailModel.customerName;
        self.phone = self.mailModel.customerPhone;
    }else {
        self.name = self.userModel.userName;
        self.phone = self.userModel.userMobile;
    }
    
}
-(void)initTableview{
    kSelfWeak;
    self.tableview = [[UITableView alloc] init];
    self.tableview.delegate = self;
    self.tableview.dataSource = self;
    _tableview.estimatedRowHeight = 0;
    _tableview.estimatedSectionHeaderHeight = 0;
    _tableview.estimatedSectionFooterHeight = 0;
    if (@available(iOS 11.0, *)) {
        self.tableview.contentInsetAdjustmentBehavior = UIApplicationBackgroundFetchIntervalNever;
    } else {
        
        self.automaticallyAdjustsScrollViewInsets = false;
    }
    self.tableview.backgroundColor = MAIN_COLOR();
    self.tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
     [self.tableview registerClass:[EditUserMessageCell class] forCellReuseIdentifier:@"EditUserMessageCell"];
    [self.view addSubview:self.tableview];
    self.tableview.frame = CGRectMake(0, 0, Screen_width, 0);
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view).mas_offset(self.navH);
        make.bottom.equalTo(weakSelf.view).mas_equalTo(-self.BotH);
        make.left.right.equalTo(weakSelf.view);
    }];
    
    if (![self.mainTitle isEqualToString:@"查看员工信息"]) {
        UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, Screen_width, 200)];
        self.tableview.tableFooterView = footerView;
        UIButton *singOut = [[UIButton alloc] initWithFrame:CGRectMake(27.5, 60, Screen_width - 55, 40)];
        [singOut setBackgroundImage:[UIImage imageWithColor:MAIN_NAV_COLOR()] forState:UIControlStateNormal];
        [singOut setBackgroundImage:[UIImage imageWithColor:MAIN_HIGHTLIGHT_COLOR()] forState:UIControlStateHighlighted];
        
        singOut.layer.masksToBounds = YES;
        singOut.layer.cornerRadius = 5;
        [singOut setTitle:@"保  存" forState:UIControlStateNormal];
        [singOut.titleLabel setFont:kFontSize(16)];
        [singOut addTarget:self action:@selector(SaveUserMessage) forControlEvents:UIControlEventTouchUpInside];
        [footerView addSubview:singOut];
    }
}



-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 50;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 2;
    
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSArray *titles = @[@"姓名",@"电话"];
    NSArray *holders = @[@"请输入姓名",@"请输入手机号"];
    
    EditUserMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"EditUserMessageCell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.mainLabel.text = titles[indexPath.row];
    cell.centerTF.placeholder = holders[indexPath.row];
    cell.centerTF.userInteractionEnabled = YES;
    cell.centerTF.tag = indexPath.row;
    cell.centerTF.delegate = self;

    if ([self.mainTitle isEqualToString:@"查看员工信息"]) {
        cell.centerTF.userInteractionEnabled = NO;
    }
    if (indexPath.row == 0) {
        cell.centerTF.keyboardType = UIKeyboardTypeDefault;
        if (self.type == 1) {
            cell.centerTF.text = self.mailModel.customerName;

        }else{
        
            cell.centerTF.text = self.userModel.userName;
        }
        [cell.centerTF removeTarget:self action:@selector(centerTFTextDidChange:) forControlEvents:UIControlEventEditingDidEnd];
    }else
        cell.centerTF.keyboardType = UIKeyboardTypeNumberPad;
    [cell.centerTF addTarget:self action:@selector(centerTFTextDidChange:) forControlEvents:UIControlEventEditingDidEnd];
        if (self.type == 1) {
            cell.centerTF.text = self.mailModel.customerPhone;

        }else{
      
            cell.centerTF.text = self.userModel.userMobile;
        }
    return cell;
    
}
-(void)textFieldDidEndEditing:(UITextField *)textField{
    if (textField.tag == 0) {
        self.name = textField.text;
    }else if (textField.tag == 1){
        self.phone = textField.text;
    }
}

- (void)centerTFTextDidChange:(UITextField *)sender {
    
    if (sender.text.length > 11) {
        sender.text = [sender.text substringToIndex:11];
    }
}

-(void)SaveUserMessage{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];//关闭键盘
    if (self.type == 1) {
        
        [self initMailPeople];
    }else{
 
        [self AddAndUpdataUser];
    }
}

-(void)AddAndUpdataUser{

    NSString *url;
    NSDictionary *params;
    if (!self.name) {
        [ShowMessage showHintMessage:@"请输入姓名!" duration:2.0 withRemindId:remindWarning];

        return;
    }
    if (!self.phone) {
        [ShowMessage showHintMessage:@"请输入电话!" duration:2.0 withRemindId:remindWarning];

        return;
    }
    

    if ([self.mainTitle isEqualToString:@"添加员工"]) {
        url = [NSString stringWithFormat:@"%@%@",Api,addStaffApi];
        params = @{
                   @"marketId":[NRWCarUser sharedUser].marketId,
                   @"userName":self.name,
                   @"userMobile":self.phone,
                   @"userType":@(41),
                   @"shopId":[NRWCarUser sharedUser].shopId ? [NRWCarUser sharedUser].shopId : @""
                   };
    }else if ([self.mainTitle isEqualToString:@"编辑员工信息"]){
        url = [NSString stringWithFormat:@"%@%@",Api,updateStaffApi];
        params = @{
                     @"userId":self.userModel.userId,
                     @"userName":self.name,
                     @"userMobile":self.phone
                             
                 };
    }
   
    [YQNetworking postWithUrl:url refreshRequest:YES cache:NO params:params progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
        
    } successBlock:^(id response) {
        if ([response[@"code"] isEqual:@1]) {
            
            [ShowMessage showHintMessage:response[@"msg"] duration:2.0 withRemindId:remindSuccess];

            self.block();
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [ShowMessage showHintMessage:response[@"msg"] duration:2.0 withRemindId:remindFail];

        }
    } failBlock:^(NSError *error) {
        [ShowMessage showHintMessage:@"请求失败!" duration:2.0 withRemindId:remindFail];
    }];
}

-(void)initMailPeople{
    
    
    if (!self.name) {
        [ShowMessage showHintMessage:@"请输入姓名!" duration:2.0 withRemindId:remindWarning];

        return;
    }
    if (!self.phone) {
        [ShowMessage showHintMessage:@"请输入电话!" duration:2.0 withRemindId:remindWarning];

        return;
    }
    if ([self.mainTitle isEqualToString:@"新建联系人"]) {
        NSString *url = [NSString stringWithFormat:@"%@%@",CRMContextApi,mailInitApi];
        NSDictionary *params = @{
                                 @"customerName":self.name,
                                 @"customerPhone":self.phone,
                                 @"userId":[NRWCarUser sharedUser].userId
                                 };
        [YQNetworking postWithUrl:url refreshRequest:YES cache:NO params:params progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
            
        } successBlock:^(id response) {
            if ([response[@"code"] isEqual:@1]) {
                self.block();
                [self.navigationController popViewControllerAnimated:YES];
            }
            
        } failBlock:^(NSError *error) {
            [ShowMessage showHintMessage:@"请求失败!" duration:2.0 withRemindId:remindFail];
        }];
    }else if ([self.mainTitle isEqualToString:@"编辑联系人"]){
        NSString *url = [NSString stringWithFormat:@"%@%@",CRMContextApi,mailUpdateApi];
        NSDictionary *params = @{
                                 @"customerName":self.name,
                                 @"customerPhone":self.phone,
                                 @"phoneRecordId":self.mailModel.phoneRecordId
                                 };
        [YQNetworking postWithUrl:url refreshRequest:YES cache:NO params:params progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
            
        } successBlock:^(id response) {
            if ([response[@"code"] isEqual:@1]) {
                self.block();
                [self.navigationController popViewControllerAnimated:YES];
            }
            
        } failBlock:^(NSError *error) {
            [ShowMessage showHintMessage:@"请求失败!" duration:2.0 withRemindId:remindFail];
        }];
        
    }
  
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    EditUserMessageCell *nextCell = [self.tableview cellForRowAtIndexPath:indexPath];
    [nextCell.centerTF becomeFirstResponder];
}


@end
